﻿using AutomaticPush.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace AutomaticPush.Extension
{
    /// <summary>
    /// 字符串辅助类
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// 将对象转换为JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static string ToJson(this object obj)
        {
            if (obj == null)
            {
                throw new ArgumentException("传入obj为空，无法继续处理请求返回！");
            }

            return JsonSerializer.Serialize(obj, GlobalData.DefaultJsonOption);
        }


        /// <summary> 
        /// DateTime转换为13位时间戳（单位：毫秒）
        /// </summary>
        /// <param name="dateTime"> DateTime</param>
        /// <returns>13位时间戳（单位：毫秒）</returns>
        public static long ToLongTimeStamp(this DateTime dateTime)
        {
            DateTime timeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)(dateTime.ToUniversalTime() - timeStampStartTime).TotalMilliseconds;
        }

        /// <summary>
        /// DateTime转换为13位时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string ToTimeStampString(this DateTime dateTime)
        {
            var str = dateTime.ToLongTimeStamp().ToString();
            return str;
        }
 

        /// <summary>
        /// 把DateTime?类型转换为"yyyy-MM-dd"
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToyyyyMMdd(this DateTime? obj)
        {
            if (obj == null)
                return "";
            DateTime.TryParse(obj.ToString(), out DateTime time);
            return time.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// yyyy-MM-dd HH:mm:ss
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToyMdHms(this DateTime? obj)
        {
            if (obj == null)
                return "";
            DateTime.TryParse(obj.ToString(), out DateTime time);
            return time.ToString("yyyy-MM-dd HH:mm:ss");
        }


        /// <summary>
        ///  字符串转时间类型
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this string str)
        {
            if (str.IsNullOrEmpty())
            {
                return DateTime.MinValue;
            }
            DateTime.TryParse(str.Trim(), out DateTime time);
            return time;
        }
        public static DateTime ToDateTimeExt(this string str)
        {
            if (str.IsNullOrEmpty())
            {
                return DateTime.MinValue;
            }
            DateTime.TryParse(str.Trim(), out DateTime time);
            return time;
        }

        /// <summary>
        /// 将JSON转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static T ToObj<T>(this string json)
        {
            if (json.IsNullOrEmpty())
            {
                throw new ArgumentException("传入Json为空，无法继续处理请求返回！");
            }
            return JsonSerializer.Deserialize<T>(json);
        }

        /// <summary>
        /// 判断字符是否为空或者空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrWhiteSpace(this string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }

        /// <summary>
        /// 将Bool返回是否字符串
        /// </summary>
        /// <param name="bl"></param>
        /// <returns></returns>
        public static string BoolToString(this bool? bl)
        {
            if (bl == null)
                bl = false;
            var sb = (bool)bl ? "是" : "否";
            return sb;
        }

        /// <summary>
        /// 将Bool返回是否字符串
        /// </summary>
        /// <param name="bl"></param>
        /// <returns></returns>
        public static string BoolToString(this bool bl)
        {
            var sb = bl ? "是" : "否";
            return sb;
        }
        /// <summary>
        /// 将List数据拼接为完整的string
        /// </summary>
        /// <param name="list"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Join(this IList<string> list, string value)
        {
            return string.Join(value, list);
        }

        public static string Format(this string text, params object[] args)
        {
            return string.Format(text, args);
        }

        /// <summary>
        /// 判断字符是否为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        /// <summary>
        /// 时间格式转换"yyyy-MM-dd HH:mm:ss"字符串
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string GetDateStr(this DateTime date)
        {
            return date.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// Guid 转Raw(16)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GuidToRaw(this Guid id)
        {
            return BitConverter.ToString(id.ToByteArray()).Replace("-", "");
        }
        /// <summary>
        /// 字符串转十六进制Byte数组
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(this string id)
        {
            try
            {
                id = id.Replace(" ", "");
                if ((id.Length % 2) != 0)
                    id += " ";
                byte[] returnBytes = new byte[id.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(id.Substring(i * 2, 2), 16);
                return returnBytes;
            }
            catch
            {
                return null;
            }

        }

        /// <summary>
        /// 获取特性 (DisplayAttribute) 的名称；如果未使用该特性，则返回枚举的名称。
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetDisplayName(this Enum enumValue)
        {
            FieldInfo fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            object[] temp = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
            DisplayAttribute[] attrs = temp as DisplayAttribute[];
            return attrs.Length > 0 ? attrs[0].Name : enumValue.ToString();
        }

        /// <summary>
        /// 获取特性 (Description) 的说明；如果未使用该特性，则返回枚举的名称。
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetDisplayDescription(this Enum enumValue)
        {
            FieldInfo fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            object[] temp = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
            DisplayAttribute[] attrs = temp as DisplayAttribute[];
            return attrs.Length > 0 ? attrs[0].Description : enumValue.ToString();
        }


        /// <summary>
        /// (Orcale)数据库Raw的string转GUID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Guid DbRawStrToGuid(this string id)
        {
            return new Guid(id.strToToHexByte());
        }

        //十六进制Byte数组
        public static Guid ByteToGuid(this byte[] id)
        {
            return new Guid(id);
        }

        /// <summary>
        /// 获取字符在数组中位置
        /// </summary>
        /// <param name="array"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int GetArrayIndex(this string[] array, object value)
        {
            return Array.IndexOf(array, value);
        }

        /// <summary>
        /// 字符串转Enum
        /// </summary>
        /// <typeparam name="T">枚举</typeparam>
        /// <param name="str">字符串</param>
        /// <returns>转换的枚举</returns>
        public static T ToEnum<T>(this string str) where T : Enum
        {
            return (T)Enum.Parse(typeof(T), str);
        }

        /// <summary>
        /// 字符串转GUID
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Guid ToGuid(this string str)
        {
            return new Guid(str);
        }



    }
}
